package org.springframework.aop.framework;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class A18_1 {


    static class Target{
        public void foo(){
            System.out.println("Target foo");
        }
    }

    static class Advice1 implements MethodInterceptor{
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            System.out.println("advice1 before...");
            Object proceed = invocation.proceed();
            System.out.println("advice1 after...");
            return proceed;
        }
    }

    static class Advice2 implements MethodInterceptor{
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            System.out.println("advice2 before...");
            Object proceed = invocation.proceed();
            System.out.println("advice2 after...");
            return proceed;
        }
    }

    static class MyInvocation implements MethodInvocation{

        private Object target;
        private Method method;
        private Object[] args;
        List<MethodInterceptor> methodInterceptorList;
        private int count = 1;

        public MyInvocation(Object target, Method method, Object[] args, List<MethodInterceptor> methodInterceptorList) {
            this.target = target;
            this.method = method;
            this.args = args;
            this.methodInterceptorList = methodInterceptorList;
        }

        @Override
        public Method getMethod() {
            return method;
        }

        @Override
        public Object[] getArguments() {
            return args;
        }

        @Override
        public Object proceed() throws Throwable {  // 调用每一个环绕通知，调用目标
            if(count > methodInterceptorList.size()){
                return method.invoke(target,args);
            }
            MethodInterceptor methodInterceptor = methodInterceptorList.get(count++ - 1);
            return methodInterceptor.invoke(this);
        }

        @Override
        public Object getThis() {
            return target;
        }

        @Override
        public AccessibleObject getStaticPart() {
            return method;
        }
    }

    public static void main(String[] args) throws Throwable {
        List<MethodInterceptor> lists = new ArrayList<>();
        lists.add(new Advice1());
        lists.add(new Advice2());
        MyInvocation myInvocation = new MyInvocation(new Target(),Target.class.getMethod("foo"),new Object[0],lists);
        myInvocation.proceed();
    }

}
